package de.mp3player.app.commands;

import java.util.*;


public class CmdManager {
	private static CmdManager cmdManager = null;
	
	List<ICommand> commands = new ArrayList<ICommand>();
	int index = 0;
	
	public static CmdManager getInstance(){
		if(cmdManager == null)
			cmdManager = new CmdManager();
		return cmdManager;
	}
	public void pushCommand(ICommand cmd){
		if(index < commands.size())
			commands = commands.subList(0,index);
		commands.add(cmd);
		index++;
	}
	public void undo() throws UndoRedoException{
		if(index > 0){
			index--;
			ICommand cmd = commands.get(index);
			cmd.undo();
		} else {
			throw new UndoRedoException("Kein Undo");
		}
	}
	public void redo() throws UndoRedoException{
		if (index < commands.size()){
			ICommand cmd = commands.get(index);
			cmd.execute();
			index++;
		} else {
			throw new UndoRedoException("Kein Redo");
		}
	}
	public void execAndPush(ICommand cmd){
		cmd.execute();
		pushCommand(cmd);
	}
	public String toString(){
		String str = "CommandStack(\n";
		for(int i=0; i < commands.size(); i++){
			if(i == index)
				str += "----------------------\n";
			str += "  " + i + ".: " + commands.get(i).describe() + "\n";
		}
		str += ")";
		return str;
	}
}
